package com.attendancesystem.controller;

import com.attendancesystem.model.*;
import com.attendancesystem.service.AttendanceDetailService;
import com.attendancesystem.util.JDBCUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;



import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;



@WebServlet(name = "TeacherInfoController", value = "/TeacherInfoController")
public class TeacherInfoController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();
        String teacherId=(String) session.getAttribute("username");
        System.out.println("teacherId:"+teacherId);
        Teacher teacher = null;

        String sql = "SELECT * FROM teachers WHERE employee_id = ?";
        try (Connection con = JDBCUtils.getConnection(); // 必须从连接池获取
             PreparedStatement stm = con.prepareStatement(sql)) {
            stm.setString(1, teacherId); // 参数绑定
            ResultSet res = stm.executeQuery();
            while (res.next()) {
                teacher = new Teacher(
                        res.getString("employee_id"),
                        res.getString("name"),
                        res.getString("department"),
                        res.getString("title"),
                        res.getString("email"),
                        res.getString("phone"),
                        res.getString("office")
                );
            }
        }
        catch (SQLException e) {
            throw new ServletException("数据库访问失败", e);
        }
        request.setAttribute("teacher", teacher);


        List<Course> courses = new ArrayList<>();
        sql="Select * from courses where teacher_id = ?";
//        System.out.println("sql:"+sql);
        try(
                Connection con = JDBCUtils.getConnection(); // 必须从连接池获取
                PreparedStatement stm = con.prepareStatement(sql);
        ){
            stm.setString(1,teacherId);
            ResultSet res=stm.executeQuery();
            while (res.next()){
              Course  course=new Course(
                        res.getInt("course_id"),
                        res.getString("course_code"),
                        res.getString("course_name"),
                        res.getInt("credit"),
                        res.getString("teacher_id")
                );
                courses.add(course);

            }

        }catch (SQLException e){
            System.out.println("数据库出现异常"+e);
        }
//        System.out.println("courses:"+courses);

        request.setAttribute("courses", courses);
        List<Lecture> lectures = new ArrayList<>();
        sql="SELECT l.*,c.course_name\n" +
                "FROM lectures l\n" +
                "JOIN courses c ON l.course_id = c.course_id\n" +
                "WHERE c.teacher_id = ?";
        try(
                Connection con = JDBCUtils.getConnection(); // 必须从连接池获取
                PreparedStatement stm = con.prepareStatement(sql)
                ){
            stm.setString(1,teacherId);
            ResultSet res=stm.executeQuery();
            while (res.next()){
                Lecture lecture=new Lecture(
                        res.getInt("lecture_id"),
                        res.getInt("course_id"),
                        res.getString("class_name"),
                        res.getTimestamp("lecture_time").toLocalDateTime(),
                        res.getString("classroom"),
                        Lecture.LectureStatus.fromChineseName(res.getString("status")),
                        res.getString("course_name"),
                        res.getString("summary")
                );

                lectures.add(lecture);
            }
        }catch (SQLException e)
        {
            System.out.println("数据库出现异常"+e);
        }
//        stream()：将集合转为顺序流（sequential stream），底层使用Spliterator实现数据分割
//        filter()：接收Predicate函数式接口，内部使用StreamOpFlag.IS_SHORT_CIRCUIT标志位优化处理
//        collect()：使用Collectors.toList()收集器，底层通过ReduceOps实现可变汇聚操作
        List<Lecture> filteredLectures = lectures.stream()
                .filter(DistinctByKeyService(Lecture::getClassName))
                .collect(Collectors.toList());

        System.out.println("lectures:"+filteredLectures);
        request.setAttribute("lectures", lectures);
        request.setAttribute("lecture", filteredLectures);


        AttendanceDetailService attendanceDetailService = new AttendanceDetailService();
        try {
            List<AttendanceDetails> details=attendanceDetailService.getAttendanceDetail();
            for (AttendanceDetails detail : details){
                System.out.println("details:"+detail);
            }

            request.setAttribute("AttendanceDetail", details);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }




        request.getRequestDispatcher("/WEB-INF/views/Teacher.jsp").forward(request,response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       doGet(request,response);
    }
//    方法内部使用了一个`ConcurrentHashMap`来跟踪已经见过的键，返回一个`Predicate`，当键不存在时返回true，从而实现去重。
    private static <T> Predicate<T> DistinctByKeyService(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
}
